package com.iuhao.orange.aspect;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;


/**
 * <pre>
 *     author : Tuo
 *     e-mail : 839539179@qq.com
 *     time   : 2018/5/8 11:49
 *     desc   : 该类记录请求 使用AOP切点实现
 *     version: 1.0
 * </pre>
 */

@Aspect
@Component
public class HttpAspect {
    private static final Logger logger = LoggerFactory.getLogger(HttpAspect.class);


    @Pointcut(value = "execution(* com.springboot.controller.*.*.*(..))")
    public void log() {

    }

    /**
     * 记录请求
     *
     * @param joinPoint
     */
    @Before(value = "log()")
    public void deBefore(JoinPoint joinPoint) {

        logger.info("----------请求开始----------");

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();

        logger.info("url={}", request.getRequestURL());
        logger.info("method={}", request.getMethod());
        logger.info("ip={}", request.getRemoteAddr());
        logger.info("class-method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        logger.info("请求参数={}",  Arrays.toString(joinPoint.getArgs()));
        logger.info("body={}", joinPoint.getArgs());
    }


    @After(value = "log()")
    public void doAfter() {
        logger.info("----------请求结束----------");
    }

    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
        logger.info("【返回结果】response={}", object.toString());
    }
}
